package com.pzhu.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzhu.dormitory.dao.MenuRoleRelationshipDao;
import com.pzhu.dormitory.entity.MenuEntity;
import com.pzhu.dormitory.entity.MenuRoleRelationshipEntity;
import com.pzhu.dormitory.service.MenuRoleRelationshipService;
import com.pzhu.dormitory.service.MenuService;
import com.pzhu.dormitory.utils.PageUtils;
import com.pzhu.dormitory.utils.Query;
import com.pzhu.dormitory.vo.MenuRolesGrantVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("menuRoleRelationshipService")
public class MenuRoleRelationshipServiceImpl extends ServiceImpl<MenuRoleRelationshipDao, MenuRoleRelationshipEntity> implements MenuRoleRelationshipService {

    @Autowired
    private MenuService menuService;

    @Override
    public PageUtils<MenuRoleRelationshipEntity> queryPage(Map<String, Object> params) {
        IPage<MenuRoleRelationshipEntity> page = this.page(
                new Query<MenuRoleRelationshipEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils<>(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGrantRole(MenuRolesGrantVo menuRolesGrantVo) {
        getMenuRoleRelationshipEntities(menuRolesGrantVo);
    }

    private void getMenuRoleRelationshipEntities(MenuRolesGrantVo menuRolesGrantVo) {
        this.remove(new LambdaQueryWrapper<MenuRoleRelationshipEntity>().eq(MenuRoleRelationshipEntity::getMenuId, menuRolesGrantVo.getMenuId()));
        List<MenuRoleRelationshipEntity> userRoleRelationEntityList = menuRolesGrantVo.getRoleIds().stream().map(roleId -> {
            MenuRoleRelationshipEntity entity = new MenuRoleRelationshipEntity();
            menuService.list(new QueryWrapper<MenuEntity>().lambda().eq(MenuEntity::getPid, menuRolesGrantVo.getMenuId()))
                    .forEach(menuEntity -> {
                        MenuRolesGrantVo rolesGrantVo = new MenuRolesGrantVo();
                        rolesGrantVo.setMenuId(menuEntity.getId());
                        rolesGrantVo.setRoleIds(menuRolesGrantVo.getRoleIds());
                        getMenuRoleRelationshipEntities(rolesGrantVo);
                    });
            entity.setMenuId(menuRolesGrantVo.getMenuId());
            entity.setRoleId(roleId);
            return entity;
        }).collect(Collectors.toList());
        this.saveBatch(userRoleRelationEntityList);
    }

}
